package table_creator;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class TableCreator {

	public static void main(String[] args) {
		String sql = creator(Member.class);
	}

	/**
	 * 生成器
	 * 
	 * @param args
	 */
	public static String creator(Class<?> clazz) {

		// if (null == className || className.length() < 1) {
		// System.err.println("arguments: annotated classes");
		// System.exit(0);
		// }
		// Class<?> clazz = clazz;
		// try {
		// // cl = Class.forName(cl);
		// } catch (ClassNotFoundException e) {
		// System.err.println(e.getMessage());
		// e.printStackTrace();
		// }
		DBTable dbTable = clazz.getAnnotation(DBTable.class);
		if (dbTable == null) {
			System.out.println("No DBTable annotations in class " + clazz.getName());
			return "No DBTable annotations in class " + clazz.getName();
		}
		String talbeName = dbTable.name();
		// If the name is empty, use the Class name:
		if (talbeName.length() < 1) {
			talbeName = clazz.getName().toUpperCase();// 讲所有的英文字符转换成大写字母
		}
		List<String> columnDefs = new ArrayList<String>();
		// 获取所有字段
		for (Field field : clazz.getDeclaredFields()) {
			String columnName = null;
			Annotation[] anns = field.getDeclaredAnnotations();
			if (anns.length < 1) {
				continue; // Not a db table column
			}
			if (anns[0] instanceof SQLInteger) {
				SQLInteger sInt = (SQLInteger) anns[0];
				// Use field name if name not specified
				if (sInt.name().length() < 1) {
					columnName = field.getName().toUpperCase();
				} else {
					columnName = sInt.name();
				}
				columnDefs.add(columnName + " INT" + getConstraints(sInt.constraints()));
			}
			if (anns[0] instanceof SqlString) {
				SqlString sStr = (SqlString) anns[0];
				if (sStr.name().length() < 1) {
					columnName = field.getName().toUpperCase();
				} else {
					columnName = sStr.name();
				}
				columnDefs.add(columnName + " VARCHAR(" + sStr.value() + ")" + getConstraints(sStr.constraints()));
			}
		}
		StringBuilder createConmand = new StringBuilder("CREATE TABLE " + talbeName + " (");
		for (String columnDef : columnDefs) {
			createConmand.append("\n " + columnDef + ",");
		}
		String tableCreate = createConmand.substring(0, createConmand.length() - 1) + ");";
		System.out.println("Table Creation SQL for " + clazz.getName() + " is :\n" + tableCreate);
		return tableCreate;
	}

	/**
	 * 
	 * @param con
	 * @return
	 */
	private static String getConstraints(Constraints con) {
		String constraints = "";
		if (!con.allowNull()) {
			constraints += " NOT NULL ";
		}
		if (con.primaryKey()) {
			constraints += " primaryKey ".toUpperCase();
		}
		if (con.unique()) {
			constraints += " unique ".toUpperCase();
		}
		return constraints;
	}
}
